import requests
import re
import os
import pygame
import time
import msvcrt
from mutagen.mp3 import MP3
pygame.mixer.init()

headers={'User-Agent':'Chrome/10'}
cookies={}#有必要可以加入cookies

def read_txt():#读取同一路径下sites.txt里面的网址
    sites=open('../sites.txt','r',encoding='utf-8')
    sites=sites.readlines()
    addresses=[]
    for line in sites:
        addresses.append(line.replace('\n',''))
    return addresses

def checkfile(filename):#检查文件是否存在，防止重复下载
    status=0
    path = os.getcwd()
    files = os.listdir(path)
    for file in files:
        if file != filename:
            status=0
        elif file == filename:
            status=1
            break
    return status

def info_hooker(address):#获取并解析网页
    address=address.replace('\n','')
    content=requests.get(address,headers=headers).text
    with open('patch.txt','w',encoding='utf-8')as w:
        w.write(content)
        w.close()
    music_info_compile=re.compile(r'<a href="/song\?id=(\d+)">(.+?)</')#在H5查找音乐信息
    music_info=re.findall(music_info_compile,content)
    return music_info

def get_music(id,name):#需要会员的歌曲要能自动跳过
    if checkfile(id+"_"+name+'.mp3')==0:
        file=requests.get('https://music.163.com/song/media/outer/url?id='+id+'.mp3',headers=headers).content
        with open(id+'_'+name+'.mp3','wb')as web:
            web.write(file)
            web.close()

def testwrite(address):#导出一份网页内容，测试用
    content=requests.get(address,headers=headers).text
    with open("NEWeb.txt","w",encoding="utf-8")as new:
        new.write(content)
        new.close()

def dir():#创建文件夹
    if not os.path.exists("Song_Cache"):
        os.mkdir("Song_Cache")
    os.chdir("Song_Cache")

def duration(filename):
    file=MP3(filename)
    return file.info.length

def skip_song(timeout):
    #切歌模块，既可以自动下一首，也可以回车下一首
    #灵感来自CSDN大神，以后有机会再原创
    start_time = time.time()
    input = ''
    while True:
        if msvcrt.kbhit():
            input = msvcrt.getche()
        if len(input) != 0 or (time.time() - start_time) > timeout:
            break
    #if len(input) > 0:
    #    return input
    #else:
    #    return 0

while checkfile('sites.txt')==0:
    print('找不到sites.txt，请补充后回车')
    input()
dir()
for line in read_txt():
    print("当前播放来源:"+line)
    info=info_hooker(line)
    for id,name in info:
        status=get_music(id,name)
        print("正在播放："+name)
        pygame.mixer.music.load(id+'_'+name+".mp3")
        try:
            pygame.mixer.music.play()
            skip_song(duration(id+'_'+name+".mp3")+0.5)
        except Exception as errcode:
            #print(errcode) 需要错误码的话，可以恢复这一行
            print("自动跳过会员歌曲")